import axios from 'axios'
import Vue from 'vue'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 50000
})

service.interceptors.request.use(
  config => {
    const token = Vue.ls.get('TOKEN')
    if (token) {
      config.headers['token'] = `${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
  // console.log('ok response', response)
  // console.log('ok response.data', response.data)
  if (response.data.code === 4) {
    showAlert(response.data.message)
    console.log('清除token')
    Vue.ls.set('TOKEN', '')
    router.push({ path: '/login' })
  } else {
    return response.data
  }
}, error => {
  // var code = error.response.data.code
  console.log('error', error)
  console.log('error.response', error.response)
  console.log('error.response.status', error.response.status)
  if (error.response.status === 404) {
    showAlert('接口404, 请确保接口可用')
    return Promise.reject(error)
  }
  if (error.toString().indexOf('timeout') > -1) {
    showAlert('网络请求超时')
    return Promise.reject(error)
  }
  showAlert('接口请求失败, error.response: ', error.response)
  return Promise.reject(error)
})
function showAlert(alertText) {
  // 创建DOM元素
  var alertDom = document.createElement('div')
  alertDom.innerHTML = alertText
  // 添加样式
  alertDom.style.cssText = `  
                    position: fixed;  
                    top: 20px;  
                    left: 50%;  
                    transform: translateX(-50%); 
                    padding: 16px 30px;
                    border-radius: 4px;
                    background-color: #fff;  
                    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
                    transition: opacity .3s,transform .3s,left .3s,right .3s,top .4s,bottom .3s;
                    color: #721c24;
                    border: 1px solid #f5c6cb;
                    font-size: 14px;  
                    z-index: 1000;  
                `
  // 将DOM元素添加到页面中
  document.body.appendChild(alertDom)
  // 设置显示延迟，不阻塞主线程
  setTimeout(function() {
    alertDom.remove() // 在一定时间后移除该元素，避免阻塞主线程
  }, 4000) // 这里设置为4秒后自动移除
}
export default service
